<template>
  <div class="logs-container">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>系统日志</span>
          <div class="header-actions">
            <el-button type="primary" @click="handleExport">
              导出日志
            </el-button>
            <el-button type="danger" @click="handleClear">
              清空日志
            </el-button>
          </div>
        </div>
      </template>

      <!-- 搜索栏 -->
      <el-form :inline="true" class="search-form">
        <el-form-item label="日志类型">
          <el-select v-model="searchForm.type" clearable>
            <el-option label="全部" value="" />
            <el-option label="系统" value="system" />
            <el-option label="登录" value="login" />
            <el-option label="操作" value="operation" />
            <el-option label="错误" value="error" />
          </el-select>
        </el-form-item>
        <el-form-item label="用户">
          <el-input v-model="searchForm.user" placeholder="用户名/ID" clearable />
        </el-form-item>
        <el-form-item label="时间范围">
          <el-date-picker
            v-model="searchForm.timeRange"
            type="datetimerange"
            range-separator="至"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>

      <!-- 日志列表 -->
      <el-table :data="logList" style="width: 100%">
        <el-table-column prop="time" label="时间" width="180" />
        <el-table-column prop="type" label="类型" width="100">
          <template #default="scope">
            <el-tag :type="getLogType(scope.row.type)">
              {{ scope.row.type }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="user" label="用户" width="120" />
        <el-table-column prop="ip" label="IP地址" width="140" />
        <el-table-column prop="action" label="操作" />
        <el-table-column prop="status" label="状态" width="100">
          <template #default="scope">
            <el-tag :type="scope.row.status === 'success' ? 'success' : 'danger'">
              {{ scope.row.status === 'success' ? '成功' : '失败' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="100" fixed="right">
          <template #default="scope">
            <el-button
              type="primary"
              link
              @click="handleViewDetail(scope.row)"
            >
              详情
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :total="total"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 日志详情对话框 -->
    <el-dialog
      v-model="detailDialogVisible"
      title="日志详情"
      width="60%"
    >
      <div v-if="currentLog" class="log-detail">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="时间">
            {{ currentLog.time }}
          </el-descriptions-item>
          <el-descriptions-item label="类型">
            <el-tag :type="getLogType(currentLog.type)">
              {{ currentLog.type }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="用户">
            {{ currentLog.user }}
          </el-descriptions-item>
          <el-descriptions-item label="IP地址">
            {{ currentLog.ip }}
          </el-descriptions-item>
          <el-descriptions-item label="操作">
            {{ currentLog.action }}
          </el-descriptions-item>
          <el-descriptions-item label="状态">
            <el-tag :type="currentLog.status === 'success' ? 'success' : 'danger'">
              {{ currentLog.status === 'success' ? '成功' : '失败' }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="详细信息" :span="2">
            <pre class="log-message">{{ currentLog.message }}</pre>
          </el-descriptions-item>
        </el-descriptions>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  getLogList,
  getLogDetail,
  exportLogs,
  clearLogs
} from '@/api/log'

// 搜索表单
const searchForm = reactive({
  type: '',
  user: '',
  timeRange: []
})

// 分页数据
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)
const loading = ref(false)

// 日志列表数据
const logList = ref([])

// 详情对话框
const detailDialogVisible = ref(false)
const currentLog = ref(null)

// 初始化数据
onMounted(() => {
  loadLogs()
})

// 加载日志列表
const loadLogs = async () => {
  try {
    loading.value = true
    const params = {
      page: currentPage.value,
      size: pageSize.value,
      type: searchForm.type,
      user: searchForm.user,
      startTime: searchForm.timeRange?.[0],
      endTime: searchForm.timeRange?.[1]
    }
    
    const { list, total: totalCount } = await getLogList(params)
    logList.value = list
    total.value = totalCount
  } catch (error) {
    console.error('加载日志失败:', error)
  } finally {
    loading.value = false
  }
}

// 获取日志类型样式
const getLogType = (type) => {
  const typeMap = {
    system: '',
    login: 'success',
    operation: 'warning',
    error: 'danger'
  }
  return typeMap[type]
}

// 搜索
const handleSearch = () => {
  currentPage.value = 1
  loadLogs()
}

// 重置搜索
const resetSearch = () => {
  searchForm.type = ''
  searchForm.user = ''
  searchForm.timeRange = []
  handleSearch()
}

// 查看详情
const handleViewDetail = async (log) => {
  try {
    const detail = await getLogDetail(log.id)
    currentLog.value = detail
    detailDialogVisible.value = true
  } catch (error) {
    console.error('获取日志详情失败:', error)
  }
}

// 导出日志
const handleExport = async () => {
  try {
    const params = {
      type: searchForm.type,
      user: searchForm.user,
      startTime: searchForm.timeRange?.[0],
      endTime: searchForm.timeRange?.[1]
    }
    
    const response = await exportLogs(params)
    // 创建下载链接
    const url = window.URL.createObjectURL(new Blob([response]))
    const link = document.createElement('a')
    link.href = url
    link.setAttribute('download', `system_logs_${new Date().getTime()}.xlsx`)
    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link)
    window.URL.revokeObjectURL(url)
    
    ElMessage.success('日志导出成功')
  } catch (error) {
    console.error('导出日志失败:', error)
  }
}

// 清空日志
const handleClear = async () => {
  try {
    await ElMessageBox.confirm(
      '确定要清空所有日志吗？此操作不可恢复。',
      '警告',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    await clearLogs()
    ElMessage.success('日志已清空')
    loadLogs()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('清空日志失败:', error)
    }
  }
}

// 分页大小改变
const handleSizeChange = (val) => {
  pageSize.value = val
  loadLogs()
}

// 当前页改变
const handleCurrentChange = (val) => {
  currentPage.value = val
  loadLogs()
}
</script>

<style scoped>
.logs-container {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-actions {
  display: flex;
  gap: 10px;
}

.search-form {
  margin-bottom: 20px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.log-detail {
  padding: 20px;
}

.log-message {
  margin: 0;
  white-space: pre-wrap;
  font-family: monospace;
  background-color: #f5f7fa;
  padding: 10px;
  border-radius: 4px;
}
</style> 